<template>
  <div>
    <el-card>
      <h1>分类管理</h1>
      <el-input v-model="search" placeholder="搜索分类" style="width: 300px; margin-bottom: 20px;"></el-input>
      <el-button type="primary" @click="fetchCategories">查询</el-button>
      <el-button type="success" @click="addCategory">新增</el-button>
      <el-button type="danger" @click="deleteSelected">删除</el-button>
      
      <el-table :data="categories" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="index" label="索引" width="80">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="分类名称"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewDetails(scope.row.id)">详情</el-button>
            <el-button type="text" size="small" @click="editCategory(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="deleteCategory(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @current-change="fetchCategories"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="total"
        style="margin-top: 20px;"
      />
    </el-card>
  </div>
</template>

<script>
import categoryApi from '@/api/categoryApi';

export default {
  data() {
    return {
      categories: [],
      search: '',
      currentPage: 1,
      pageSize: 5,
      total: 0,
    };
  },
  methods: {
    fetchCategories() {
      categoryApi.getCategories(this.search, this.currentPage,this.pageSize).then(response => {
        if (response.data && response.data.data) {
          console.log("eeeeeeeeeeee",response)
          this.categories = response.data.data.records; // 假设返回的数据结构
          this.total = response.data.data.total; // 假设返回的数据结构
          this.currentPage = response.data.data.current;
        } else {
          console.error('数据格式不正确', response.data);
        }
      }).catch(error => {
        console.error('请求失败', error);
      });
    },
    addCategory() {
      this.$router.push('/add-category');
    },
    editCategory(category) {
      this.$router.push({ path: '/edit-category', query: { id: category.id } });
    },
    deleteCategory(id) {
      categoryApi.deleteCategory(id).then(() => {
        this.fetchCategories(this.currentPage); // 刷新列表
      });
    },
    deleteSelected() {
      // 实现批量删除逻辑
    },
    viewDetails(id) {
      this.$router.push({ path: '/category-details', query: { id } });
    },
  },
  mounted() {
    this.fetchCategories(); // 组件挂载时获取分类列表
  },
};
</script>

<style>
/* 如果需要，可以在这里添加自定义样式 */
</style>